package com.zkzl.cdz.netty;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @program: NettyTEST
 * @description: 管理连接
 * @author: QSY
 * @create: 2019-07-25 11:33
 **/
@Slf4j
public class MangerChannel implements Runnable {
    private static ConcurrentMap<String, Channel> CHANNEL = new ConcurrentHashMap<>();
    private static ConcurrentMap<Channel, String> CHANNEL_CODE = new ConcurrentHashMap<>();

    @Override
    public void run() {
        log.info("启动管理连接");
        while (true) {
            for (String code : CHANNEL.keySet()) {
                Channel cc = getChannel(code);
                if (cc != null && !cc.isActive()) {
                    CHANNEL.remove(code);
                }
            }
            try {
                Thread.sleep(2000);
            } catch (Exception e) {

            }
        }
    }


    public static Channel getChannel(String key) {
        synchronized (CHANNEL) {
            // 初始化
            if (CollectionUtils.isEmpty(CHANNEL)) {
                return null;
            }
            Channel channel = CHANNEL.get(key);
            if (channel == null) {
                log.info("桩编码：" + key + "无对应CHANEL信息");
            }
            return channel;
        }
    }


    public static void removeChannel(String key) {
        synchronized (CHANNEL) {
            CHANNEL.remove(key);
        }
    }

    public static void addChannel(String key, Channel channel) {
        synchronized (CHANNEL) {
            if (!CHANNEL.containsKey(key)) {
                CHANNEL.put(key, channel);
            }
        }
    }

    ///////////////////////////////////////
    public static String getCode(Channel channel) {
        synchronized (CHANNEL_CODE) {
            // 初始化
            if (CollectionUtils.isEmpty(CHANNEL_CODE)) {
                log.info("无CODE信息");
                return null;
            }
            return CHANNEL_CODE.get(channel);
        }
    }


    public static void removeCode(Channel channel) {
        synchronized (CHANNEL_CODE) {
            CHANNEL_CODE.remove(channel);
        }
    }

    public static void addCode(Channel channel, String code) {
        synchronized (CHANNEL_CODE) {
            if (!CHANNEL_CODE.containsKey(channel)) {
                CHANNEL_CODE.put(channel, code);
            }
        }
    }


}
